package com.pet.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet.mapper.CartMapper;
import com.pet.mapper.ItemMapper;
import com.pet.mapper.UserMapper;
import com.pet.pojo.Cart;
import com.pet.pojo.Item;
import com.pet.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Override
    public List<Cart> cartGetAll(String userName) {
        //获取用户id
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        User user = userMapper.selectOne(queryWrapper);
        Integer userId = user.getId();
        //根据用户id查询所有该用户的购物车商品信息
        QueryWrapper<Cart> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userId);
        List<Cart> cartList = cartMapper.selectList(queryWrapper1);
        return cartList;
    }

    @Override
    public Boolean cartDeleteOne(Integer id) {
        int i = cartMapper.deleteById(id);
        if(i != 0) return true;
        return false;
    }

    @Override
    public Boolean cartDeleteAll() {
        int i = cartMapper.delete(null);
        System.out.println(i);
        if(i != 0) return true;
        return false;
    }

    @Override
    public Boolean addCart(String userName, Integer itemId) {
        //根据用户名查询用户信息
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username", userName);
        User user = userMapper.selectOne(queryWrapper1);
        Integer userId = user.getId();
        //根据商品id查询商品信息
        Item item = itemMapper.selectById(itemId);
        //根据用户信息和商品信息更新购物车表
        Cart cart = new Cart();
        cart.setUserId(userId)
                .setItemId(itemId)
                .setTitle(item.getTitle())
                .setPrice(item.getPrice())
                .setImages(item.getImages());
        QueryWrapper<Cart> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("item_id",itemId)
                .eq("user_id",userId);
        Cart cart1 = cartMapper.selectOne(queryWrapper2);
        if(cart1 == null){
            int insert = cartMapper.insert(cart);
            return true;
        }
        return false;
    }
}
